package com.ruoyi.common.utils;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.vo.DeptUserVO;
import com.ruoyi.common.utils.vo.DeptVO;
import com.ruoyi.common.utils.vo.MsgTextVO;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class QywxUtil {
    private static RedisCache redisCache = SpringUtils.getBean("redisCache");
//    private static RestTemplate restTemplate = SpringUtils.getBean("restTemplate");
//    private static String corpid = "ww0f2510fea2be59a0";
//    private static String agentld = "1000002";
//    private static String corpsecret = "0p2K2fwkJoQIUgdHHoxhcVWA7_4giADf8IskpOmaE1c";
    private static String corpid = "wwab5f053482c43339";
    private static String agentld = "1000006";
    private static String corpsecret = "Yv95hs35_kgjZh3kpd1tFVzrbSRvjIYUTWWp-PbJtMw";
    private static final char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String getToken() {
        String key = CacheConstants.QYWX_TOKEN_KEY + agentld;
        Object token = redisCache.getCacheObject(key);
        if (token != null) {
            return token.toString();
        }
        String body = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret);
        JSONObject jsonObject = JSONObject.parseObject(body);
        String accessToken = jsonObject.get("access_token").toString();
        System.out.println(accessToken);
        //DZemO4sjo_Qhrz8TO4Fz-Vo4UWu8HVz7_ownN7OykSHEqJEmRsVk4ciR-5PkeZxY5go1Vj6-SlWbSyISDcg5DcoTWkglkmuUkqkk4vBkV2d2HHRKlAjyqCSdgLdkXCZeuyU1-wOrJ7HUxhJRNZggNDGcJWONKll23LgoJlPys2zYRfpympfD7NDsb-ufWVKg1ZvbVtZlxUMLN-uzmAVW5g
        redisCache.setCacheObject(key, accessToken, 30, TimeUnit.MINUTES);
        return accessToken;
    }

//    public static void getUseIdList(String cursor){
//        String limit = "1000";
//        String body = HttpUtils.sendPost("https://qyapi.weixin.qq.com/cgi-bin/user/list_id?access_token=" + getToken()+"&limit="+limit+(cursor == "" ? "" : "&cursor="+cursor), null);
//        System.out.println(body);
//    }

    public static List<DeptVO> getDeptList(String token) {
        try {
            String body = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + token);
            JSONObject jsonObject = JSONObject.parseObject(body);
            List<DeptVO> list = JSONArray.parseArray(jsonObject.get("department").toString(), DeptVO.class);
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    public static List<DeptUserVO> getDeptUserList(String token, String deptId) {
        try {
            String body = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + token + "&department_id=" + deptId);
            JSONObject jsonObject = JSONObject.parseObject(body);
            List<DeptUserVO> list = JSONArray.parseArray(jsonObject.get("userlist").toString(), DeptUserVO.class);
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    public static Map<String,String> getUserId(String token, String code) {
        Map<String,String> map = new HashMap<>();
        try {
            String body = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" + token + "&code=" + code);
//            System.out.println(body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            map.put("userId",jsonObject.get("userid").toString());
            map.put("userTicket",jsonObject.get("user_ticket").toString());
            return map;
        } catch (Exception e) {
            return null;
        }
    }

    public static void sendMsg(String token, List<String> userIdList, String content) {
        MsgTextVO msgTextVO = new MsgTextVO();
        msgTextVO.setMsgtype("text");
        msgTextVO.setTouser(StringUtils.join(userIdList, "|"));
        msgTextVO.setAgentid(Integer.parseInt(agentld));
        Map<String, Object> map = new HashMap<>();
        map.put("content", content);
        msgTextVO.setText(map);
        String body = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token).body(JSONObject.toJSONString(msgTextVO)).execute().body();
        System.out.println(body);
    }

    public static DeptUserVO getAuthUserInfo(String token,String userTicket){
        try {
            Map<String,String> map = new HashMap<>();
            map.put("user_ticket",userTicket);
            String body = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=" + token).body(JSONObject.toJSONString(map)).execute().body();
            System.out.println(body);
            DeptUserVO deptUserVO = JSONObject.parseObject(body, DeptUserVO.class);
            return deptUserVO;
        }catch (Exception e)
        {
            return null;
        }
    }

    public static void getFile(String token,String mediaId,String saveUrl){
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=" + token + "&media_id=" + mediaId;
        ResponseEntity<byte[]> exchange = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
        byte[] data = exchange.getBody();
        InputStream inputStream = new ByteArrayInputStream(data);
        try {
            FileUtils.copyInputStreamToFile(inputStream,new File(saveUrl));
        } catch (IOException e) {
            e.printStackTrace();
        }
//        URLConnection conn = null;
//        InputStream is = null;
//        BufferedInputStream bis = null;
//        String fileSize = "";
//        try {
//            String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id="+mediaId;
//            URL realUrl = new URL(requestUrl);
//            conn = realUrl.openConnection();
//            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            conn.setRequestProperty("Content-Type",  "application/x-www-form-urlencoded; charset=utf-8");
//            conn.setRequestProperty("Accept-Charset", "UTF-8"); //
//            conn.setRequestProperty("contentType", "utf-8");
//
//            //获取网络流的头部信息
//            Map<String, List<String>> maps = conn.getHeaderFields();
//            for (String key : maps.keySet()) {
//                System.out.println(key + "---> " + maps.get(key));
//                if ("Content-Length".equals(key)) {
//                    fileSize = maps.get(key).get(0);//获取文件大小
//                }
//            }
//            // 获取网络流的内容
//            bis = new BufferedInputStream(conn.getInputStream());
//            byte[] data = getByte(bis); // 获取当前条目的字节数组
//            is = new ByteArrayInputStream(data); // 把当前条目的字节数据转换成Inputstream流
//            return is ;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        } finally {
//            if (bis != null) {
//                try {
//                    bis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (is != null) {
//                try {
//                    is.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
    }
    public static byte[] getByte(InputStream is) {
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            byte[] buf = null;
            int length = 0;
            while ((length = is.read(temp, 0, 1024)) != -1) {
                bout.write(temp, 0, length);
            }
            buf = bout.toByteArray();
            bout.close();
            return buf;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getTicket(String token){
        String key = CacheConstants.QYWX_TICKET_KEY + agentld;
        Object ticketVal = redisCache.getCacheObject(key);
        if (ticketVal != null) {
            return ticketVal.toString();
        }
        String body = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=" + token);
        JSONObject jsonObject = JSONObject.parseObject(body);
        String ticket = jsonObject.get("ticket").toString();
        redisCache.setCacheObject(key, ticket, 30, TimeUnit.MINUTES);
        return ticket;
    }

    public static String getSignature(String timestamp, String jsapiTicket, String nonceStr, String url) {
        try {
//        Map<String, String> map = new HashMap(4);
//        map.put("jsapi_ticket", jsapiTicket);
//        map.put("timestamp", timestamp);
//        map.put("noncestr", nonceStr);
//        map.put("url", url);
        String str = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;
//        String createLinkString = createLinkString(map);
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();

            crypt.update(str.getBytes("UTF-8"));
            String signature = byteToHex(crypt.digest());
            return signature;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
//        String signature = SHA1Encode(str);

    }
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
    public static String SHA1Encode(String str) {
        if (str == null) {
            return null;
        } else {
            try {
                MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
                messageDigest.update(str.getBytes());
                return getFormattedText(messageDigest.digest());
            } catch (Exception var2) {
                throw new RuntimeException(var2);
            }
        }
    }
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);

        for(int j = 0; j < len; ++j) {
            buf.append(HEX_DIGITS[bytes[j] >> 4 & 15]);
            buf.append(HEX_DIGITS[bytes[j] & 15]);
        }

        return buf.toString();
    }

    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList(params.keySet());
        Collections.sort(keys);
        String prestr = "";

        for(int i = 0; i < keys.size(); ++i) {
            String key = (String)keys.get(i);
            String value = (String)params.get(key);
            if (i == keys.size() - 1) {
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }

        return prestr;
    }

    public static void main(String[] args) {
        MsgTextVO msgTextVO = new MsgTextVO();
        msgTextVO.setMsgtype("text");
        msgTextVO.setTouser("111");
        msgTextVO.setAgentid(Integer.parseInt("1111"));
        Map<String, Object> map = new HashMap<>();
        Map<String, String> content = new HashMap<>();
        map.put("content", "1111");
//        map.put("text",content);
        msgTextVO.setText(map);
        System.out.println(JSONObject.toJSONString(msgTextVO));
//        getUseIdList("");
    }
}
